package com.itheima.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ForkJoinTask extends RecursiveTask<Integer> {

    private int THRESHOLD = 20;

    private int start;//0

    private int end;//1000

    private List<String> list;


    public ForkJoinTask(int start, int end, List<String> list) {
        this.start = start;
        this.end = end;
        this.list = list;
    }

    @Override
    protected Integer compute() {
        BlockingQueue list = new ArrayBlockingQueue<String>(1024);
        if ((end - start) < THRESHOLD) {
            return add(start, end);
        }


        int middle = (start + end) / 2;
        ForkJoinTask task1 = new ForkJoinTask(start, middle);
        ForkJoinTask task2 = new ForkJoinTask(middle, end);
        invokeAll(task1, task2);

        Integer join = task1.join();
        Integer join1 = task2.join();

        return join + join1;

    }


    public Integer add(Integer a, Integer b) {
        return a + b;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        List<String> list = new ArrayList<String>();
        for (int i = 1; i <= 330; i++) {
            list.add("i------" + i);
        }
        System.out.println(list.size());
        long s1 = System.currentTimeMillis();
        // 参数默认是cpu数（可以自定义）
        ForkJoinPool pool = new ForkJoinPool();
        // 提交可分解的PrintTask任务
        Future<Integer> ss = pool.submit(new ForkJoinTask(0, list.size(), list));
        System.out.println("ss = " + ss.get());
        //线程阻塞，等待所有任务完成
        pool.awaitTermination(1, TimeUnit.SECONDS);
        // 关闭线程池
        pool.shutdown();
        long s2 = System.currentTimeMillis();
        long s = s2 - s1;
        System.out.println(s);
    }


}
